import { useEffect, useState } from 'react';
const useRequest = (cb: any, options?: any) => {
  const [data, setData] = useState<any>([]);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState(null);
  const fetchData = async (fetchOptions?: any) => {
    console.log('请求数据函数');
    setLoading(true);
    try {
      const res = await cb();

      if (fetchOptions && fetchOptions.resType == 'add') {
        setData({ ...res, data: [...data.data, ...res.data] });
      } else {
        setData(res);
      }
      options && options.onSuccess && options.onSuccess(res);
    } catch (error: any) {
      setErr(error.message);
    } finally {
      setLoading(false);
    }
  };
  /**当配置了immediate为true，加载时自动发送请求 */
  useEffect(() => {
    if (options && options.refreshDeps && options.refreshDeps.length > 0) {
      return;
    }
    if (options && options.immediate) {
      fetchData();
    }
  }, []);
  /**当配置了refreshDeps依赖项时，改变依赖项更新请求 */
  useEffect(() => {
    if (options && options.refreshDeps && options.refreshDeps.length > 0) {
      console.log('子组件searchParams执行了');
      fetchData();
    }
  }, options.refreshDeps);
  //刷新请求
  const refresh = async (fetchOptions?: any) => {
    await fetchData(fetchOptions);
  };
  return { loading, data, fetchData, err, refresh };
};

export default useRequest;
